package core;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import constants.CurrentConfigConstants;
import constants.DefaultConfigConstants;
import dto.Message;

public class ReceiveMsg {
	
	private int port = Integer.parseInt(CurrentConfigConstants.CLIENT_CURRENT_PORT);
	private byte[] buffer = new byte[DefaultConfigConstants.DEFAULT_PACKET_SIZE];
	private Message msg = null;
	
	/**
	 * 接受
	 */
	public Message receive() {
		try {
			DatagramSocket server = new DatagramSocket(port);
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			server.receive(packet);

			ByteArrayInputStream byteStream = new 
			ByteArrayInputStream(buffer);
			ObjectInputStream is = new ObjectInputStream(new 
			BufferedInputStream(byteStream));
			Object o = is.readObject();
			msg = (Message)o;

			packet.setLength(buffer.length);

			server.close();

			return this.msg;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}// end receive
}
